package com.jftone.bh.app.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jftone.annotation.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 文件存储在阿里云OSS的策略下 文件管理实现
 *
 */
@Service
public class OSSFileManagerService {

    private Log log = LogFactory.getLog(OSSFileManagerService.class);


    private final String endpoint ="https://oss-cn-shenzhen.aliyuncs.com";

    private final String accessId = "LTAIZraK4wYRHqyD";

    private final String accessKey = "p42uDoNeHBBCPWLQn4OK5fMKAdHNtl";

    private final String bucket = "biaohong";

    public final static String host = "https://biaohong.oss-cn-shenzhen.aliyuncs.com";



    public String upload(MultipartFile file, String dir, String key) {
        CredentialsProvider provider = new DefaultCredentialProvider(accessId,accessKey);
        OSSClient client = new OSSClient(endpoint, provider, null);
        try {
            client.putObject(bucket,  dir+"/"+key, file.getInputStream());
            return host+"/"+dir+"/"+key;
        } catch(Exception e) {
            log.error("upload aliyun oss file error",e);
        }
        client.shutdown();
        return "";
    }

    public String upload(InputStream input, String dir, String key) throws Exception{
        CredentialsProvider provider = new DefaultCredentialProvider(accessId,accessKey);
        OSSClient client = new OSSClient(endpoint, provider, null);
        client.putObject(bucket,  dir+"/"+key, input);
        client.shutdown();
        return host+"/"+dir+"/"+key;
    }


    public void delete(String dir) {
        CredentialsProvider provider = new DefaultCredentialProvider(accessId,accessKey);
        OSSClient client = new OSSClient(endpoint, provider, null);
        client.deleteObject(bucket, dir);
        client.shutdown();
    }

}
